/*
 * BalanceResource.cpp
 *
 *  Created on: 2013. 9. 4.
 *      Author: mega@gamevil.com
 */

#include "BalanceResource.h"
#include "../NUtil/Utils.h"
#include "../engine.h"

namespace ProjectZ { namespace NResource {

BalanceResource::BalanceResource()
{
	pBalanceAD	= new BalanceData;
	pBalanceIOS	= new BalanceData;
}

BalanceResource::~BalanceResource()
{
	delete pBalanceAD;
	delete pBalanceIOS;
}

bool BalanceResource::LoadResource()
{
	if (false == pBalanceAD->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE))
		return false;

	if (false == pBalanceIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS))
		return false;

	return true;
}

int BalanceResource::GetValue(User * pUser, int seq)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(pUser->GetUserInfo().company, pUser->GetUserInfo().sale_code);

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pBalanceAD->GetValue(seq);

	case NUtil::MarketType::IOS_KAKAO:
		return pBalanceIOS->GetValue(seq);

	default:
		return 0;
	}

	return 0;
}

int BalanceResource::GetValue(int seq)
{
	return pBalanceAD->GetValue(seq);
}

NResource::BalanceData *
BalanceResource::GetBalancePtr(User * pUser)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(pUser->GetUserInfo().company, pUser->GetUserInfo().sale_code);

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pBalanceAD;

	case NUtil::MarketType::IOS_KAKAO:
		return pBalanceIOS;

	default:
		return NULL;
	}

	return NULL;
}



bool BalanceData::LoadResource(int company, int saleCode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT NATIONAL_CODE, num, value FROM resource_balance WHERE company=%d AND sale_cd=%d", company, saleCode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	clsValueTree.clear();

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		int seq, value;
		clsAuto->GetRecord() >> NATIONAL_CODE >> seq >> value;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsValueTree[seq] = value;
	}

	return true;
}

int BalanceData::GetValue(int seq)
{
	auto iter = clsValueTree.find(seq);

	if (iter == clsValueTree.end())
		return 0;

	return iter->second;
}

} /* NResource */ } /* ProjectZ */
